#include "ssicloud_energy_analysis.h"

using namespace ssicloud;
EnergyAnalysis::EnergyAnalysis()
    : ListObject<EmergyLNode>(LQ_BASE_URL "/energyAnalysis/totalByDay"
                              , OBJECT_NAME_EnergyAnalysis
                              , NetUrl::NET_HTTP_METHOD_POST)
{
    mUrl.appendHeader(HEADER_JSON);
    mUrl.appendHeader(HEADER_TOKEN);
}

bool EnergyAnalysis::requestAll(const char *start, const char *end)
{
    snprintf(m_body, sizeof(m_body), "{\"vin\": \"%s\","
                                     "\"start\": \"%s\","
                                     "\"end\": \"%s\""
                                     "}", VIN_STRING, start, end);
    mUrl.appendBody(m_body);
    return obtain();
}

int EnergyAnalysis::genResult(NetBuffer *data)
{
    int ret = KL_DATA_PRISER_OK;
    //GEN_Printf(LOG_DEBUG, "size: %lu\n%s", data->size(), (char *)data->buffer());
    cJSON *root = cJSON_Parse((char *)data->buffer(), data->size());
    cJSON *categories = cJSON_GetObjectItem(root, "data");
    if (categories)
    {
        for (cJSON *item = categories->child; NULL != item; item = item->next )
        {
            EmergyLNode tmp;

            JSON_VALUETRING_SWAP_BYTESTRING(item, fuels, tmp.fuels);
            JSON_VALUETRING_SWAP_BYTESTRING(item, miles, tmp.miles);
            JSON_VALUETRING_SWAP_BYTESTRING(item, kmFuel, tmp.kmFuel);
            JSON_VALUETRING_SWAP_BYTESTRING(item, day, tmp.day);

            // GEN_Printf(LOG_DEBUG, "items size=%d", tmp.items.size());
            mNodes.push_back(tmp);
        }
        if (mNodes.empty())
        {
            GEN_Printf(LOG_WARN, "load Category is empty.");
            ret = KL_DATA_PRISER_EMPTY;
        }/* else
        {
            profile();
        }*/
    } else
    {
        GEN_Printf(LOG_ERROR, "priser failed, size: %lu\n%s", data->size(), data->buffer());
        ret = KL_DATA_PRISER_JSOC_ERROR;
    }

    cJSON_Delete(root);
    return ret;

}

void EnergyAnalysis::profile()
{
    ListTable<EmergyLNode>::iterator it = mNodes.begin();
    GEN_Printf(LOG_INFO, "---------能耗分析---------");
    for (; it != mNodes.end(); ++it)
    {
        GEN_Printf(LOG_DUMP, "日期:%s, 能耗:%s, 里程:%s,百公里能耗:%s", it->day.string(), it->fuels.c_str(), it->miles.c_str(), it->kmFuel.string());
    }
    GEN_Printf(LOG_INFO, "---------完成-------");
}
